package com.teamclub.pay.sservices


import java.util

import io.ebean.{Ebean, Expression, ExpressionList}
import com.fasterxml.jackson.databind.JsonNode
import com.teamclub.domain.pay.order.PayOrder
import com.teamclub.pay.sforms.PayOrderForm
import com.teamclub.pay.sservices.third.IPayService
import com.teamclub.util.Springs
import com.teamclub.util.errors.ErrorCode
import com.teamclub.util.libs.F
import org.apache.commons.lang3.StringUtils
import org.slf4j.LoggerFactory
import org.springframework.beans.BeanUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service


@Service
class XPayService {
  val logger = LoggerFactory.getLogger(getClass)
  @Autowired
  var springs: Springs = _


  def appPay(form: PayOrderForm): F.Either[JsonNode, ErrorCode] = {
    val order = new PayOrder()
    BeanUtils.copyProperties(form, order)
    order.save()
    val newOrder = Ebean.find(classOf[PayOrder], order.getId)
    val orderNum = form.getOrganNo + System.currentTimeMillis() + "%04d".format(order.getId % 50)
    newOrder.setOrderNum(orderNum)
    newOrder.update()
    form.setOrderNum(orderNum)
    val paySerivce = springs.getBean(form.getThirdType + ".payservice").asInstanceOf[IPayService]
    //查询相关的支付参数
    val resp = paySerivce.appPay(form)
    resp
  }

  def thirdQueryOrder(form: PayOrderForm): F.Either[PayOrder, ErrorCode] = {
    if(StringUtils.isBlank(form.orderNum) && StringUtils.isBlank(form.thirdOrderNum)) {
      return F.Either.Right(ErrorCode.ref("订单号需要传输"))
    }
    val where = Ebean.find(classOf[PayOrder]).where()
    expr(where, form)
    val payOrder = where.findOne()
    if(0 != payOrder.getPayResult) {  //若已变化，则直接返回
      return F.Either.Left(payOrder)
    }
    val paySerivce = springs.getBean(form.getThirdType + ".payservice").asInstanceOf[IPayService]
    val respOrder = paySerivce.thirdQuery(form, payOrder)
    return respOrder
  }

  def expr(where: ExpressionList[PayOrder], form: PayOrderForm) = {
    if(StringUtils.isNotBlank(form.orderNum)) {
      where.eq("orderNum", form.orderNum)
    }
    if(StringUtils.isNotBlank(form.thirdOrderNum)) {
      where.eq("thirdOrderNum", form.thirdOrderNum)
    }
  }

}
